'use strict';
const moment = require('moment');
const async = require('async');
const superagent = require('superagent');
const YjxActivityModel = require('../../../common/yjxMysql/mapping/YjxActivityModel');
const YjxActUserProductModel = require('../../../common/yjxMysql/mapping/YjxActUserProductModel');
const YjxActRewardRuleModel = require('../../../common/yjxMysql/mapping/YjxActRewardRuleModel');
const YjxActUserReward = require('../../../common/yjxMysql/mapping/YjxActUserReward');
const luaUtil = require('../../service/commonUtils/luaUtil');
const retUtil = require('../commonUtils/retUtil');
const YjxCouponModel = require('../../../common/yjxMysql/mapping/YjxCouponModel');
const YjxUserLikeModel = require('../../../common/yjxMysql/mapping/YjxUserLikeModel');
const yjxV1UtilLuaUtil = require('../../yjx/v1/util/luaUtil');
const assetUtil = require('../commonUtils/assetUtil');


const activityServiceUtil = (function () {

    function activityServiceUtil() {

    }



    /**
     * 201-获取活动详情
     *
     * @author 毛凯
     * @date 2018-07-19
     *
     *
     * @param {Object} option 请求参数
     * @param {Number} option.device               设备标识
     * @param {Number} option.activityId            活动唯一标识
     * @param {Number} option.topLimit              限制获取前 topLimit 位作品, 默认为3
     * @param {String} option.withPromote         是否请求获取推广信息, 0 不获取, 1 获取, 默认为0
     * @param {Function} callback 回调函数
     *                      error: 失败原因
     */
    activityServiceUtil.getActivityDetail = function (option, callback) {
        const totalTasks = [];

        // 1. 获取活动信息
        totalTasks.push(function (callback) {

            activityServiceUtil.getSingleActivityDetailInfoById(option.activityId, function (error, activity) {
                const data = {};
                data.activity = activity;
                return callback(error, data);
            });
        });
        // 2. 获取活动统计信息
        totalTasks.push(function (data, callback) {
            const entity = new YjxActivityModel();
            entity.getActivityStatisticsInfo({activityId : option.activityId}, function (error, info) {
                data.statisticsInfo = info;
                // 注意: 此处应根据参与平台类型来决定 totalData1 与 totalData2 对应字段, 暂不处理
                data.statisticsInfo.totalLike = info.totalData1 || 0;
                data.statisticsInfo.totalComment = info.totalData2 || 0;
                delete data.statisticsInfo.totalData1;
                delete data.statisticsInfo.totalData2;
                return callback(error, data);
            });
        });
        // 3. 获取活动排行表
        totalTasks.push(function (data, callback) {
            const entity = new YjxActUserProductModel();
            const opt = {
                activityId : option.activityId,
                pageNum : 0,
                pageSize : option.topLimit
            };
            entity.getActivityProductList(opt, function (error, products) {
                data.products = products;
                return callback(error, data);
            });
        });
        // 4. 获取活动推荐码配置信息
        totalTasks.push(function (data, callback) {
            activityServiceUtil.getActivityPromoteInfo(option.activityId,function (err,res) {
                data.promoteInfo = res;
                return callback(null,data);
            });
        });
        // 5. 重组数据
        totalTasks.push(function (data, callback) {
            data.retData = {};
            data.retData.activity = data.activity;
            data.retData.brief = data.statisticsInfo;
            data.retData.promoteInfo = data.promoteInfo;
            data.retData.topProducts = [];

            for (let i=0; i < data.products.length; i ++) {
                let p = data.products[i];

                data.retData.topProducts.push({
                    id : p.aup_id,
                    thumb : p.theme_img_cust || p.theme_img,
                    url : p.url,
                    video : p.video,
                    state : p.state,
                    note : p.note,
                    rewardAmount : p.reward_amt,
                    unit : p.unit,
                });
                // 抖音
                if(p.platform_type === 10) {
                    data.retData.topProducts[i].like = Number(p.data1);
                    data.retData.topProducts[i].comment = Number(p.data2);
                }
            }
            return callback(null, data);
        });
        // 6. redis记录活动的浏览次数
        totalTasks.push(function (data, callback) {
            yjxV1UtilLuaUtil.statisticsActivityInfo(option.activityId,function (err,result) {
                if (err || result){
                    console.log(err || "lua存储活动信息失败:"+err);
                    return callback(null,data);
                }
                return callback(null,data);
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            if(error) {
                return callback(error, null);
            }
            //######## 活动参与人数过少, 暂时以作品数冒充参与人数 ###############
            data.retData.brief.totalUsers = Math.ceil(data.retData.brief.totalProducts*0.9);
            //######## 活动参与人数过少, 暂时以作品数冒充参与人数 ###############
            return callback(error, data.retData);
        });
    };


    /**
     * 根据活动 id 查询单个活动详细信息
     *
     * @author 毛凯
     * @date 2018-07-18
     *
     * @param {Number} activityId 活动 id
     * @param {Function} callback 回调函数
     *                      error: 获取失败
     *                      data : 活动基础信息 + 活动规则信息
     */
    activityServiceUtil.getSingleActivityDetailInfoById = function (activityId, callback) {
        const totalTasks = [];

        // 1. 基础信息
        totalTasks.push(function (callback) {

            const entity = new YjxActivityModel();
            entity.getSingleActivitySettingInfo(activityId, function (error, actInfo) {
                const data = {};
                data.actInfo = actInfo;

                // 筹备中
                if(data.actInfo && data.actInfo.state === 60) {
                    return callback('大赛筹备中, 敬请期待', null);
                }
                return callback(error, data);
            });
        });
        // 2. 获取规则信息
        totalTasks.push(function (data, callback) {
            const entity = new YjxActRewardRuleModel({
                as_id : data.actInfo.as_id,
                type :  10, //10为实际的奖励，20为推荐码奖励
                state : 10, // 10 有效
                del_flg : 0
            });
            entity.getOrderBy = function () {return ' `min` ';};
            entity.findFromDB(function (error, rules) {
                if(error || !rules || rules.length <=0) {
                    return callback(error||'该活动状态异常', null);
                }
                data.rules = rules;
                return callback(error, data);
            });
        });
        // 3. 重组活动信息
        totalTasks.push(function (data, callback) {
            data.retData = {};

            data.retData.id = data.actInfo.act_id;
            data.retData.state = data.actInfo.state; // 默认为 10
            data.retData.thumb = data.actInfo.theme_img;
            data.retData.shareImg = data.actInfo.share_img;
            data.retData.url = data.actInfo.url;
            data.retData.title = data.actInfo.title;
            data.retData.startDate = data.actInfo.startDate;
            data.retData.endDate = data.actInfo.endDate;
            data.retData.startTimestamp = data.actInfo.startTimestamp;
            data.retData.endTimestamp = data.actInfo.endTimestamp;

            data.retData.type = data.actInfo.type;
            data.retData.platformType = data.actInfo.platform_type;
            data.retData.images = retUtil.safe_parser_JSON_string(data.actInfo.images) || [];
            data.retData.orgName = data.actInfo.org_name;
            data.retData.productLimit = data.actInfo.product_limit;
            data.retData.rewardTotal = data.actInfo.reward_total;

            return callback(null,data);
        });

        // 4. 拼接奖励规则
        totalTasks.push(function (data, callback) {
            let rewardRule = '';
            for (let i=0; i< data.rules.length; i++) {
                let r = data.rules[i];
                rewardRule += r.arr_name + "  " + r.desc;
                rewardRule += i === data.rules.length-1 ? '' : '\n';
            }
            let rule = '在短视频平台中';
            let condition = '参赛者根据拍摄要求在短视频平台获得至少获得';
            if(data.actInfo.field1) {
                rule += '每';
                // 抖音
                if(data.actInfo.platform_type === 10) {
                    if(data.actInfo.threshold1 > 0) {
                        condition += data.actInfo.threshold1 + '点赞、';
                    }
                    rule += '赞'
                }
                // 其他平台配置
                else {
                    if(data.actInfo.threshold1 > 0) {
                        condition += data.actInfo.threshold1 + '点赞、';
                    }
                    rule += '赞'
                }
                rule += '得' + data.actInfo.weight1 + '分、';
            }
            if(data.actInfo.field2) {
                rule += '每';
                // 抖音
                if(data.actInfo.platform_type === 10) {
                    if(data.actInfo.threshold2 > 0) {
                        condition += data.actInfo.threshold2 + '评论、';
                    }
                    rule += '评论'
                }
                // 其他平台配置
                else {
                    if(data.actInfo.threshold2 > 0) {
                        condition += data.actInfo.threshold2 + '评论、';
                    }
                    rule += '评论'
                }
                rule += '得' + data.actInfo.weight2 + '分、';
            }
            if(condition.length > 21) {
                condition = condition.substr(0, condition.length -1);
                condition += '才能参与评奖';
            }
            rule = rule.substr(0, rule.length -1);
            rule += '，总分越高排名越靠前';

            data.retData.introduce = [
                {title : '主办方', content : data.actInfo.org_name},
                {title : '大赛名称', content : data.actInfo.title},
                {title : '大赛日期', content : data.actInfo.startDate + '-' + data.actInfo.endDate},
                {title : '奖金总额', content : data.actInfo.reward_total/100 + '元'},
                {title : '奖励分配', content : rewardRule},
                {title : '获奖条件', content : condition},
                {title : '参与上限', content : '每个账号最多'+data.actInfo.product_limit+'个作品'},
                {title : '评分规则', content : rule},
                {title : '大赛描述', content : data.actInfo.desc}
            ];
            // 没有门槛, 移除参与条件
            if(condition.length <= 2) {
                data.retData.introduce.splice(5, 1);
            }
            return callback(null, data);
        });

        async.waterfall(totalTasks, function (error, data) {
            if(error) {
                return callback(error, null);
            }
            return callback(error, data.retData);
        });
    };


    /**
     * 201-获取活动推广信息
     *
     * @author 毛凯
     * @date 2018-07-19
     *
     * @param {Number} activityId 活动 id
     * @param {Function} callback 回调函数
     *                      error: 获取失败
     *                      data : 活动基础信息 + 活动规则信息
     */
    activityServiceUtil.getActivityPromoteInfo = function (activityId, callback) {
        //1.获取发放推荐码配置
        const totalTasks = [];
        const entity = new YjxActivityModel();
        totalTasks.push(function (callback) {
            const data = {};
            const codeReward = {
                "enablePromoter" : 0,           // 是否可使用推荐人奖池 (有奖池金额, 有分配规则, 且规则与金额对的上)
                "promoterMin": 0,               // 推荐人奖励名次最小值
                "promoterMax": 0,             // 推荐人奖励名次最小值
                "promoterReward": 0        // 推荐人奖励金额, 单位: 分
            };
            entity.getActivityCcodeConfigInfo(activityId,20/*类型20推荐码奖励配置*/,function (err,result) {
                if (err || !result || !result[0]){
                    data.codeReward = codeReward;
                    return callback(null,data);
                }
                codeReward.enablePromoter = 1;
                codeReward.promoterMin = result[0].min;
                codeReward.promoterMax = result[0].max;
                codeReward.promoterReward = result[0].reward_amt;
                data.codeReward = codeReward;
                return callback(null,data);
            });
        });
        //2.获取填写推荐码配置
        totalTasks.push(function (data,callback) {
            const writeCodeReward = {
                "enablePromoted" : 0,           // 是否可使用被推荐人奖池 (有奖池金额, 有分配规则, 且规则与金额对的上)
                "promotedMin": 0,               // 被推荐人奖励名次最小值
                "promotedMax": 0,             // 被推荐人奖励名次最小值
                "promotedReward": 0,        // 被推荐人奖励金额, 单位: 分
            };
            entity.getActivityCcodeConfigInfo(activityId,21/*类型21填写推荐码奖励配置*/,function (err,result) {
                if (err || !result || !result[0]){
                    data.writeCodeReward = writeCodeReward;
                    return callback(null,data);
                }
                writeCodeReward.enablePromoted = 1;
                writeCodeReward.promotedMin = result[0].min ;
                writeCodeReward.promotedMax = result[0].max ;
                writeCodeReward.promotedReward = result[0].reward_amt;
                data.writeCodeReward = writeCodeReward;
                return callback(null,data);
            });
        });
        //3.获取剩余的奖励数量
        totalTasks.push(function (data,callback) {
            const entity = new YjxActUserReward({
                act_id : activityId,
                r_type : 20, // 20发送推广码收益
                bal_flg : 1,
                del_flg : 0,
            });
            entity.findCountFromDB(function (error, cnt) {
                if(error) return callback(error);
                const limit = data.writeCodeReward.promotedMax - cnt;
                data.writeCodeReward.promotedRemain = limit;
                data.codeReward.promoterRemain = limit;
                return callback(null, data);
            });
        });
        //4.处理最后的结果
        totalTasks.push(function (data,callback) {
            const retData = {
                "enablePromoter" : data.codeReward.enablePromoter,           // 是否可使用推荐人奖池 (有奖池金额, 有分配规则, 且规则与金额对的上)
                "promoterRemain" : data.codeReward.promoterRemain,           // 推荐人奖励剩余份数
                "promoterMin": data.codeReward.promoterMin,               // 推荐人奖励名次最小值
                "promoterMax": data.codeReward.promoterMax,             // 推荐人奖励名次最小值
                "promoterReward": data.codeReward.promoterReward,        // 推荐人奖励金额, 单位: 分

                "enablePromoted" : data.writeCodeReward.enablePromoted,           // 是否可使用被推荐人奖池 (有奖池金额, 有分配规则, 且规则与金额对的上)
                "promotedRemain" :  data.writeCodeReward.promotedRemain,          // 被推荐奖励剩余份数
                "promotedMin": data.writeCodeReward.promotedMin,               // 被推荐人奖励名次最小值
                "promotedMax": data.writeCodeReward.promotedMax,             // 被推荐人奖励名次最小值
                "promotedReward": data.writeCodeReward.promotedReward        // 被推荐人奖励金额, 单位: 分
            };
            data.retData = retData;
            return callback(null,data);
        });
        async.waterfall(totalTasks, function (error, data) {
            if(error) {
                return callback(error, null);
            }
            return callback(error, data.retData);
        });
    };


    /**
     * 201-获取活动作品列表
     *
     * @author 毛凯
     * @date 2018-07-19
     *
     *
     * @param {Object} option 请求参数
     * @param {Number} options.device               设备标识
     * @param {Array} options.actId            活动唯一标识数组的 json 字符串, 不传默认全部活动
     * @param {Number} options.pageNum            页码
     * @param {Number} options.pageSize            页容量
     * @param {Number} options.withTotalPage      是否获取总页数, 0 不获取, 1 获取, 默认为 0
     * @param {Array} options.states            作品状态数组的 json 字符串, 10新建, 20评审中, 30通过, 40不通过
     * @param {Number} options.userId            用户唯一标识, 若传递则标记筛选该用户的作品
     * @param {Number} options.orderBy            0 按作品当前排名排序, 1 按作品的创建时间排序, 默认为 0
     * @param {Function} callback 回调函数
     *                      error: 失败原因
     */
    activityServiceUtil.getActivityProductList = function (options, callback) {
        const totalTasks = [];
        let actId = options.actId;
        actId = actId.toString();
        let state = options.states;
        state = state.toString();
        const opt = {
            actId : actId || 0,
            userId : options.userId || 0,
            state : state || 0,
            pageNum : options.pageNum,
            pageSize : options.pageSize,
            orderBy : Number(options.orderBy || '0')
        };
        // 获取列表
        totalTasks.push(function (callback) {
            const entity = new YjxActUserProductModel();
            const data = {};
            data.retData = {};
            entity.getActUserProductByParamList(opt, function (error, list) {
                if (error){
                  return callback(error, null);
                }
                if(!list || list.length <= 0){
                    data.retData.list = [];
                    return callback(null,data);
                }
                data.retData.list = list;
                return callback(null, data);
            });
        });
        // 按需获取总页数
        totalTasks.push(function (data, callback) {
            if(!options.withTotalPage) {
                return callback(null, data);
            }
            const entity = new YjxActUserProductModel();
            entity.getActUserProductByParamCnt(opt, function (error, count) {
                data.retData.totalPage = Math.floor((count-1)/options.pageSize)+1;
                data.retData.currentPage = options.pageNum;
                return callback(error, data);
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            if(error) {
                return callback(error, null);
            }
            return callback(error, data.retData);
        });
    };

    /**
     * 201-获取被推荐用户列表
     *
     * @author 毛凯
     * @date 2018-07-20
     *
     *
     * @param {Object} option 请求参数
     * @param {Number} option.device               设备标识
     * @param {Number} option.pageNum            页码
     * @param {Number} option.pageSize            页容量
     * @param {Number} option.withTotalPage      是否获取总页数, 0 不获取, 1 获取, 默认为 0
     * @param {Number} option.userId            用户唯一标识, 若传递则标记筛选该用户的作品
     * @param {Function} callback 回调函数
     *                      error: 失败原因
     */
    activityServiceUtil.getPromtedUserList = function (option, callback) {
        const entity = new YjxActUserReward();
        const totalTasks = [];
        //1.获取用户私有码
        totalTasks.push(function (callback) {
            const entity = new YjxCouponModel({
                use : 20,
                user_id : option.userId,
                del_flg : 0
            });
            const data = {};
            data.retData = {};
            data.option = option;
            entity.findFromDB(function (error, reslut) {
                if(error ) {
                    return callback(error, null);
                }
                if (!reslut || reslut.length <=0){
                    data.retData.list = [];
                    return callback(null,data);
                }
                data.option.code = reslut[0].c_code;
                return callback(null, data);
            });
        });
        //2.获取用户私有码推荐列表
        totalTasks.push(function (data,callback) {
            if(!data || !data.option || !data.option.code){
                return callback(null,data);
            }
            entity.getUserOwnCodeRewardList(data.option,function (err,result) {
                if (err){
                    return callback(err, null);
                }
                if (!result || result.length <= 0){
                    data.retData.list = [];
                    return callback(null,data);
                }
                data.retData.list = result;
                return callback(null,data);
            });
        });
        //2.计算总页数
        totalTasks.push(function (data,callback) {
            if (!option.withTotalPage){
                return callback(null,data);
            }
            entity.getUserOwnCodeRewardCnt(data.option,function (err,count) {
                data.retData.totalPage = Math.floor((count-1)/option.pageSize)+1 || 0;
                data.retData.currentPage = option.pageNum;
                return callback(null,data);
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            if(error) {
                return callback(error, null);
            }
            return callback(error, data.retData);
        });
    };


    /**
     * 201-获取活动推荐方排行榜
     *
     * @author 毛凯
     * @date 2018-07-20
     *
     *
     * @param {Object} option 请求参数
     * @param {Number} option.device               设备标识
     * @param {Number} option.userId               用户id
     * @param {Number} option.actId               活动 id
     * @param {Number} option.order               暂定如下 1 金额排名
     * @param {Number} option.privacy              是否使用隐私模式 0 不使用, 返回用户信息时不对昵称扥进行隐藏处理 1 使用, 返回用户信息时对昵称等进行隐藏处理
     * @param {Number} option.pageNum            页码
     * @param {Number} option.pageSize            页容量
     * @param {Number} option.withTotalPage      是否获取总页数, 0 不获取, 1 获取, 默认为 0
     * @param {Function} callback 回调函数
     *                      error: 失败原因
     */
    activityServiceUtil.getActPromoterRankingList = function (option, callback) {
        const entity = new YjxActivityModel();
        const totalTasks = [];
        //1.获取列表
        totalTasks.push(function (callback) {
            entity.getActivityAllUserSendCodeRewardList(option,function (err,result) {
                if (err){
                    return callback(err, null);
                }
                const data = {};
                data.codeList = [];
                data.retData={};
                if (!result || result.length <= 0){
                    data.retData.list = [];
                    return callback(null,data);
                }
                data.codeList = result;
                return callback(null,data);
            });
        });
        //2.脱敏数据处理
        totalTasks.push(function (data,callback) {
            if (!data.codeList ||  data.codeList <= 0){
                return callback(null,data);
            }
            if (!option.privacy ){
                data.retData.list =data.codeList;
                return callback(null,data);
            }
            const retDataList = [];
            for (let i = 0;i<data.codeList.length;i++){
                let oneInfo = data.codeList[i];
                let name = oneInfo.nickName;
                if (name && name.length > 2){
                    let nameH = name.substring(0,1);
                    let nameF = name.substring(name.length-1,name.length);
                    let nameM = ( "*****************").substr(0,name.length-2 );
                    let newName = nameH+nameM+nameF;
                    oneInfo.nickName = newName;
                }
                retDataList.push(oneInfo);
            }
            data.retData.list = retDataList;
            return callback(null,data);
        });
        //2.计算总页数
        totalTasks.push(function (data,callback) {
            if (!option.withTotalPage){
                return callback(null,data);
            }
            entity.getActivityAllUserSendCodeRewardCnt(option,function (err,count) {
                data.retData.totalPage = Math.floor((count-1)/option.pageSize)+1 || 0;
                data.retData.currentPage = option.pageNum;
                return callback(null,data);
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            if(error) {
                return callback(error, null);
            }
            return callback(error, data.retData);
        });
    };


    /**
     * 202-初始化活动配置信息
     *
     * @author 毛凯
     * @date 2018-07-20
     *
     * @param actId 活动id
     * @param {Function} callback 回调函数
     *                      error: 失败原因
     */
    activityServiceUtil.initActivityInfo = function (actId,callback) {
        const totalTasks = [];
        const entity = new YjxActivityModel();
        //获取活动信息
        totalTasks.push(function (callback) {
            entity.get202MiniProgramActivityInfo(actId,function (err,results) {
                if (err){
                    return callback(err ,null);
                }
                if (!results || results.length <= 0){
                    return callback("未获取到活动信息" ,null);
                }
                const data = {};
                data.activityInfo  = {
                    id : results[0].id,
                    state : results[0].state,
                    thumb : results[0].thumb,
                    url :  results[0].url,
                    title : results[0].title,
                    type : results[0].type,
                    platformType : results[0].platformType,
                    images : results[0].images,
                    orgName : results[0].orgName,
                    productLimit : results[0].productLimit,
                    randomReward : results[0].randomReward,
                    randomRemaining : results[0].randomRemaining,
                    likeReward : results[0].likeReward,
                    likeRemaining : results[0].likeRemaining,
                    praisedReward : results[0].praisedReward,
                    praisedRemaining: results[0].praisedRemaining,
                    startTime :results[0].start_time,
                    endTime :results[0].end_time,
                    introduce :results[0].desc,
                    shareImage : results[0].shareImage
                };
                return callback(null,data);
            });
        });
        //查询具体规则
        totalTasks.push(function (data,callback) {
            entity.get202MiniProgramActivityRule(actId,function (err,results) {
                if (err){
                    return callback(err,null);
                }
                if (!results || results.length <= 0){
                    return callback("未获取到活动信息" ,null);
                }
                for (let i = 0;i<results.length;i++){
                    let rule = results[i];
                    if (rule.type === 30){//随机红包奖励最小最大值
                        data.randomMin = rule.min_reward;
                        data.randomMax = rule.max_reward;
                        data.randomCenter = rule.rnd_center;
                    }
                    if (rule.type === 31){//点赞红包最小最大值
                        data.likeMin = rule.min_reward;
                        data.likeMax = rule.max_reward;
                        data.likeCenter = rule.rnd_center;
                    }
                    if (rule.type === 32){//被点赞红包最小最大值
                        data.praisedMin = rule.min_reward;
                        data.praisedMax = rule.max_reward;
                        data.praisedCenter =  rule.rnd_center;
                    }
                }
                return callback(null,data);
            });
        });
        //建立redis参数结构
        totalTasks.push(function (data,callback) {
            const values = [];
            values.push(data.activityInfo.id);
            values.push(data.activityInfo.randomReward);
            values.push(data.activityInfo.likeReward);
            values.push(data.activityInfo.praisedReward);
            values.push(data.randomMin);
            values.push(data.randomMax);
            values.push(data.likeMin);
            values.push(data.likeMax);
            values.push(data.praisedMin);
            values.push(data.praisedMax);
            const actInfo = JSON.stringify(data.activityInfo);
            values.push(actInfo);
            values.push( data.randomCenter);
            values.push(data.likeCenter);
            values.push(data.praisedCenter);
            data.values = values;
            return callback(null,data);
        });
        //建立redis参数结构·
        totalTasks.push(function (data,callback) {
           luaUtil.initActivityInfo(data.values,function (err,result) {
                if (err || !result){
                    return callback(err, null);
                }
                return callback(null,data);
           });
        });
        async.waterfall(totalTasks, function (error, data) {
            return callback(error, {});
        });
    };

    /**
     * 获取图片点赞活动列表
     *
     * @author 王俊
     * @date 2018-07-30
     *
     * @param {{Object}} options
     * @param {Array} options.states            活动状态数组
     * @param {Number} options.pageNum          活动列表页码
     * @param {Number} options.pageSize         活动列表页容量
     * @param {Number} options.withTotalPage    是否获取活动列表总页数
     * @param {Function} callback
     *                      error:
     *                      data
     */
    activityServiceUtil.getImagePraiseActivityList = function (options, callback) {
        const totalTasks = [];

        // 获取列表
        totalTasks.push(function (callback) {

            const entity = new YjxActivityModel();
            entity.getImagePraiseActivityList(options, function (error, list) {
                if (error) return callback(error, null);
                const data = {};
                data.actList = list || [];
                return callback(error, data);
            });
        });
        // 获取动态信息( redis)
        totalTasks.push(function (data, callback) {
            const tasks = [];
            for (let i=0; i<data.actList.length; i++) {
                const t = (function (index, act) {

                    return function (callback) {
                        const opt = {
                            activityId: act.act_id,
                            remaining: true
                        };
                        // lua 中存储活动的起止时间后, 可在获取活动信息的同时获取到, 统一活动格式, 使用: activityServiceUtil.getImagePraiseActivityDetail
                        activityServiceUtil.getImagePraiseActivityDetail(opt, function (error, info) {
                            if(error) return callback(error, null);
                            act.orgName = info.orgName;
                            act.randomReward = info.randomReward;
                            act.randomRemaining = info.randomRemaining;
                            act.likeReward = info.likeReward;
                            act.likeRemaining = info.likeRemaining;
                            act.praisedReward = info.praisedReward;
                            act.praisedRemaining = info.praisedRemaining;
                            return callback(error, info);
                        });
                    }
                })(i, data.actList[i]);
                if(t) tasks.push(t);
            }
            async.parallelLimit(tasks, 5, function (error, results) {
                return callback(error, data);
            });
        });
        // 获取总页数
        totalTasks.push(function (data, callback) {
            const entity = new YjxActivityModel();
            entity.getImagePraiseActivityListCnt(options, function (error, count) {
                data.currentPage = options.pageNum;
                data.totalPage = Math.floor((count-1)/options.pageSize)+1;
                return callback(error, data);
            });
        });
        // 重组数据结构
        totalTasks.push(function (data, callback) {
            data.retData = {};
            data.retData.list = [];
            data.retData.currentPage = data.currentPage;
            data.retData.totalPage = data.totalPage;

            for(let i=0; i<data.actList.length; i++) {
                const act = data.actList[i];

                data.retData.list.push({
                    id: act.act_id,
                    state: act.state,
                    thumb: act.theme_img,
                    url: act.url,
                    shareImage: act.share_img,
                    title: act.title,
                    orgName: act.orgName,
                    randomReward: act.randomReward,
                    randomRemaining: act.randomRemaining,
                    likeReward: act.likeReward,
                    likeRemaining: act.likeRemaining,
                    praisedReward: act.praisedReward,
                    praisedRemaining: act.praisedRemaining
                });
            }
            return callback(null, data);

        });
        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error, null);
            return callback(error, data.retData);
        });
    };

    /**
     * 获取图片点赞活动详情
     *
     * @author 王俊
     * @date 2018-07-30
     *
     * @param {{Object}} options
     * @param {{Object}} options.activityId         活动唯一标识
     * @param {Number} [options.remaining]          是否获取剩余奖励
     * @param {Number} [options.participants]       是否获取参与人数
     * @param {Number} [options.rule]               是否获取奖励规则(min-max)
     * @param {Function} callback                   回调
     *                      err
     *                      actInfo
     */
    activityServiceUtil.getImagePraiseActivityDetail = function(options, callback) {
        const totalTasks = [];

        // 获取基础信息
        totalTasks.push(function (callback) {
            luaUtil.getActInfoJson([options.activityId], function (error, info) {
                const data = {};
                data.actJson = info;
                data.actInfo = retUtil.safe_parser_JSON_string(info);
                if(!data.actInfo) error = error || '该活动不存在或已关闭';
                return callback(error, data);
            });
        });
        // 获取剩余奖励
        totalTasks.push(function (data, callback) {
            if(!options.remaining) {
                return callback(null, data);
            }
            luaUtil.getActAllRemaining([options.activityId], function (error, remaining) {
                if(error || !remaining || remaining.length !== 3) {
                    return callback(error || '获取剩余奖励出错', data);
                }
                data.remaining = {};
                data.remaining.randomRemaining = remaining[0];
                data.remaining.likeRemaining = remaining[1];
                data.remaining.praisedRemaining = remaining[2];
                return callback(null, data);
            });
        });
        // 获取参与人数
        totalTasks.push(function (data, callback) {
            if(!options.participants) {
                return callback(null, data);
            }
            luaUtil.getActAllUserCount([options.activityId], function (error, participants) {
                if(error || !participants || participants.length !== 3) {
                    return callback(error || '获取参与人数出错', data);
                }
                data.participants = {};
                data.participants.randomParticipants = participants[0];
                data.participants.likeParticipants = participants[1];
                data.participants.praisedParticipants = participants[2];
                return callback(error, data);
            });
        });

        // 获取规则信息
        totalTasks.push(function (data, callback) {
            if(!options.rule) {
                return callback(null, data);
            }
            luaUtil.getActRuleMinMax([options.activityId, 4/*获取所有规则*/], function (error, rules) {
                if(error || !rules || rules.length !== 6) {
                    return callback(error || '获取规则出错', data);
                }
                data.rules = {};
                data.rules.randomMin = rules[0];
                data.rules.randomMax = rules[1];
                data.rules.likeMin = rules[2];
                data.rules.likeMax = rules[3];
                data.rules.praisedMin = rules[4];
                data.rules.praisedMax = rules[5];
                return callback(error, data);
            });
        });

        // 拼接返回值
        totalTasks.push(function (data, callback) {
            data.retData = data.actInfo;
            data.retData.images = JSON.parse(data.actInfo.images || '[]');
            let state = data.actInfo.state;
            // 重新计算状态
            if(state <=30) {
                const current = moment();
                if(current.isBefore(data.actInfo.startTime)) {
                    state = 10;
                }
                if(current.isAfter(data.actInfo.endTime)) {
                    state = 30
                }
                if(current.isAfter(data.actInfo.startTime) && current.isBefore(data.actInfo.endTime)) {
                    state = 20
                }
            }
            data.retData.state = state;
            // 获取剩余奖励
            if(data.remaining) {
                data.retData.likeRemaining = data.remaining.likeRemaining;
                data.retData.randomRemaining = data.remaining.randomRemaining;
                data.retData.praisedRemaining = data.remaining.praisedRemaining;
            }
            // 获取参与人数
            if (data.participants) {
                data.retData.randomParticipants = data.participants.randomParticipants;
                data.retData.likeParticipants = data.participants.likeParticipants;
                data.retData.praisedParticipants = data.participants.praisedParticipants;
            }
            // 获取奖励规则
            if (data.rules) {
                data.retData.randomMin = data.rules.randomMin;
                data.retData.randomMax = data.rules.randomMax;
                data.retData.likeMin = data.rules.likeMin;
                data.retData.likeMax = data.rules.likeMax;
                data.retData.praisedMin = data.rules.praisedMin;
                data.retData.praisedMax = data.rules.praisedMax;
            }

            return callback(null, data);
        });

        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error, null);
            return callback(error, data.retData);
        })
    };

    /**
     * 获取活动被点赞列表(每赞一个, 且有金额奖励)
     *
     * @author 王俊
     * @date 2018-07-31
     *
     * 获取某图片点赞活动参与者列表
     *
     * @author 王俊
     * @date 2018-07-31
     *
     * @param {{Object}} option
     * @param {Array} option.actIds             活动 id 数组
     * @param {Number} option.rewardLimit       奖励金额限制, 大于等于最低限制才算入列表, 单位: 分
     * @param {Number} option.pageNum           页码
     * @param {Number} option.pageSize          页容量
     * @param {Number} [option.withTotalPage]   是否获取总页数
     * @param {Number} [option.orderBy]         排序方式, 1 时间倒序, 默认为 1
     * @param {Function} callback
     *                      error
     *                      data: {
     *                          list:[],
     *                          currentPage: 0,
     *                          totalPage: 1
     *                      }
     */
    activityServiceUtil.getImagePraiseActivityParticipantList = function(option, callback) {

        const totalTasks = [];
        // 获取列表
        totalTasks.push(function (callback) {
            const entity = new YjxActivityModel();
            entity.getImagePraiseActivityParticipantList(option, function (error, list) {
                const data = {};
                data.list = list || [];
                return callback(error, data);
            });
        });
        // 获取总页数
        totalTasks.push(function (data, callback) {
            if(!option.withTotalPage) {
                return callback(null, data);
            }
            const entity = new YjxActivityModel();
            entity.getImagePraiseActivityParticipantListCnt(option, function (error, count) {
                data.currentPage = option.pageNum;
                data.totalPage = Math.floor((count-1)/option.pageSize)+1;
                data.totalCount = count;
                return callback(error, data);
            });
        });

        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error, null);
            return callback(error, data);
        });
    };

    /**
     * 获取图片点赞活动的作品信息
     *
     * @author 王俊
     * @date 2018-07-31
     *
     * 注意: 参数可为  option.actId 和 option.userId 或 option.productId, 或 全部传递, 注意: 对应关系
     *
     * @param {{Object}} option
     * @param {Number} [option.actId]         活动 id
     * @param {Number} [option.userId]        用户 id
     * @param {Number} [option.productId]     作品 id
     * @param {Function} callback
     *                      error
     *                      info
     */
    activityServiceUtil.getImagePraiseActivityProductInfo = function(option, callback){
        const entity = new YjxActUserProductModel();
        entity.getImagePraiseActivityProductInfo(option, function (error, products) {
            if (error) return callback(error, null);
            if(!products || products.length <=0) return callback(error, null);
            return callback(error, products[0]);
        });
    };

    /**
     * 获取某作品点赞用户列表
     *
     * @author 王俊
     * @date 2018-07-31
     *
     * @param {{Object}} options
     * @param {Array} options.productId          作品 id
     * @param {Number} options.pageNum           页码
     * @param {Number} options.pageSize          页容量
     * @param {Number} [options.withTotalPage]   是否获取总页数
     * @param {Number} option.rewardType        10挑战活动奖励，20发放推广码奖励, 21填写推广码奖励, 30首次浏览活动分享页随机红包, 31点赞方奖励, 32被点赞方奖励',
     * @param {Number} [options.orderBy]         排序方式, 1 时间倒序, 2 点赞金额
     * @param {Function} callback
     *                      error
     *                      data: {
     *                          list:[],
     *                          currentPage: 0,
     *                          totalPage: 1
     *                      }
     */
    activityServiceUtil.getImagePraiseActivityProductLikeUserList = function(options, callback) {
        const totalTasks = [];
        // 获取列表
        totalTasks.push(function (callback) {
            const entity = new YjxActUserProductModel();
            entity.getImagePraiseActivityProductLikeUserList(options, function (error, list) {
                const data = {};
                data.list = list || [];
                return callback(error, data);
            });
        });
        // 获取总页数
        totalTasks.push(function (data, callback) {
            if(!options.withTotalPage) {
                return callback(null, data);
            }
            const entity = new YjxActUserProductModel();
            entity.getImagePraiseActivityProductLikeUserListCnt(options, function (error, count) {
                data.currentPage = options.pageNum;
                data.totalPage = Math.floor((count-1)/options.pageSize)+1;
                data.totalCount = count;
                return callback(error, data);
            });
        });

        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error, null);
            return callback(error, data);
        });
    };


    /**
     * 提交图片点赞作品
     *
     * @author 王俊
     * @date 2018-07-30
     *
     * @param {{Object}} options
     * @param {Number} options.device       设备标识
     * @param {Number} options.userId       用户唯一标识
     * @param {Number} options.activityId   活动唯一标识
     * @param {String} options.url          用户作品地址
     * @param {Function} callback           回调
     */
    activityServiceUtil.submitImagePraiseProduct = function(options, callback) {

        const totalTasks = [];

        totalTasks.push(function (callback) {
            const data = {};

            const entity = new YjxActUserProductModel({
                user_id: options.userId,
                act_id: options.activityId,
                del_flg: 0
            });
            entity.findFromDB(function (error, products) {
                if(products && products.length >= 1) {
                    error = error || '您已参加此活动, 不可重复参与';
                }
                return callback(error, data);
            });
        });
        // 图片自动审核
        totalTasks.push(function (data, callback) {
            const opt = {
                url: options.url
            };
            assetUtil.greenImageAsset(opt, function (error, result) {
                if(error) return callback(error, data);
                if(result.pass !== 1) {
                    //error = result.msg;
                    error = '图片含有违规内容, 请重新添加';
                }
                return callback(error, data);
            });
        });

        // 插入作品
        totalTasks.push(function (data, callback) {
            const entity = new YjxActUserProductModel({
                device: options.device,
                user_id: options.userId,
                act_id: options.activityId,
                type: 20,                   // 图片点赞
                url: options.url,
                state: 30,
                note: '自动审核通过'
            });
            entity.saveToDB(function (error, insertId) {
                data.productId = insertId;
                return callback(error, data);
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            return callback(error, {productId : data.productId});
        })
    };


    /**
     * 给作品点赞
     *
     * @author 毛凯
     * @date 2018-07-31
     *
     * @param {{Object}} option 请求参数
     * @param {Number} option.device               设备标识
     * @param {Number} option.userId               用户id
     * @param {Number} option.productId            作品 id
     * @param {Number} option.actId                活动 id
     * @param {Function} callback           回调
     */
    activityServiceUtil.giveALikeToProduct = function(option, callback) {
        const totalTasks = [];
        //检测该用户有无点过赞
        totalTasks.push(function (callback) {
            const entity = new YjxUserLikeModel();
            entity.checkUserProductLikeCnt(option,function (err,result) {
                if (err){
                    return callback(err, null);
                }
                const data = {};
                data.count = result;
                data.retData = {};
                if (result > 0){
                    data.retData.enableReward = 0;
                    data.retData.praisedRedPackage = 0;
                    data.retData.likeRedPackage = 0;
                    return callback(null,data);
                }
                data.retData.enableReward = 1;
                return callback(null,data);
            });
        });
        //检查点赞用户id和作品的用户id是否一样
        totalTasks.push(function (data,callback) {
            const entity = new YjxActUserProductModel();
            entity.getUserIdByUserProductId(option,function (err,result) {
                if (err){
                    return callback(err, null);
                }
                if (Number(result||'0') === Number(option.userId||'0')){
                    data.userCount = 1;
                    data.retData.enableReward = 0;
                    data.retData.praisedRedPackage = 0;
                    data.retData.likeRedPackage = 0;
                    return callback(null,data);
                }
                data.userCount = 0;
                data.retData.enableReward = 1;
                return callback(null,data);
            });
        });
        //更新点赞奖池信息并存储到数据库 2获取点赞红包
        totalTasks.push(function (data,callback) {
            if (data.count > 0 || data.userCount > 0){
                return callback(null,data);
            }
            luaUtil.calculateRedPackage([option.actId,2],function(err,result){
                if (err){
                    return callback(err);
                }
                luaUtil.tryGetRedPackage([option.actId,2,result],function (error,res) {
                    if(error){
                        return callback(error, null);
                    }
                    data.retData.likeRedPackage = Number(res||'0');
                    return callback(null,data);
                });
            });
        });
        //更新被点赞的奖金池3获取被点赞红包
        totalTasks.push(function (data,callback) {
            if (data.count > 0 || data.userCount > 0){
                return callback(null,data);
            }
            luaUtil.calculateRedPackage([option.actId,3],function(err,result){
                if (err){
                    return callback(err);
                }
                luaUtil.tryGetRedPackage([option.actId,3,result],function (error,res) {
                    if(error){
                        return callback(error, null);
                    }
                    data.retData.praisedRedPackage = Number(res||'0');
                    return callback(null,data);
                });
            });
        });
        //插入数据库
        totalTasks.push(function (data,callback) {
            if (data.count > 0 || data.userCount > 0){
                return callback(null,data);
            }
            const entity = new YjxActUserReward();
            option.likeReward = data.retData.likeRedPackage;
            option.praisedReward = data.retData.praisedRedPackage;
            entity.updateUserLikeReward(option,function (err,result) {
                if (err){
                    return callback(err, null);
                }
                var res = Number(result||'0');
               if (res === 1){
                   return callback("参数错误插入失败，请检查参数", null);
               } else if (res === 0 || res === 2){
                   data.res = result;
                   return callback(null,data);
               }
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error, null);
            return callback(error, data.retData);
        });

    };


    /**
     * 获取活动随机奖励
     *
     * @author 毛凯
     * @date 2018-07-31
     *
     * @param {{Object}} option 请求参数
     * @param {Number} option.device               设备标识
     * @param {Number} option.userId               用户id
     * @param {Number} option.actId                活动 id
     * @param {Function} callback           回调
     */
    activityServiceUtil.getActivityRandomReward = function(option, callback) {
        const totalTasks = [];
        const entity = new YjxActUserReward();
        //检测该用户有无获得该活动红包
        totalTasks.push(function (callback) {
            entity.checkUserRandomRedPackage(option,function (err,result) {
                if (err){
                    return callback(err, null);
                }
                const data = {};
                data.count = result;
                data.retData = {};
                if (result > 0){
                    data.retData.firstReward = 0;
                    data.retData.randomReward = 0;
                    return callback(null,data);
                }
                data.retData.firstReward = 1;
                return callback(null,data);
            });
        });
        //更新点赞奖池信息并存储到数据库 1随机红包
        totalTasks.push(function (data,callback) {
            if (data.count > 0){
                return callback(null,data);
            }

            luaUtil.calculateRedPackage([option.actId,1],function(err,result){
                if (err){
                    return callback(err);
                }
                luaUtil.tryGetRedPackage([option.actId,1,result],function (error,res) {
                    if(error){
                        return callback(error, null);
                    }
                    if (res <= 0) {
                        data.retData.firstReward = 0;
                        data.retData.randomReward = 0;
                        return callback(null,data);
                    }
                    data.retData.randomReward = Number(res||'0');
                    return callback(null,data);
                });
            });
        });
        //插入数据库
        totalTasks.push(function (data,callback) {
            if (data.count > 0 || data.retData.randomReward <= 0){
                return callback(null,data);
            }
            entity.getUserBalance(option.userId,function (err,result) {
                if (err){
                    return callback(err, null);
                }
                option.curReward= (result && result[0]) ? result[0].balance || 0 : 0;
                option.RandomRedReward = data.retData.randomReward ? data.retData.randomReward : 0;
                entity.addUserRandomRedPackage(option,function (err,res) {
                    if (err){
                        return callback(err, null);
                    }
                    return callback(null,data);
                });
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error, null);
            return callback(error, data.retData);
        });

    };

    /**
     * 检测用户是否为某作品点赞
     *
     * @author 王俊
     * @date 2018-07-31
     *
     * @param {{Object}} options
     * @param {Number} options.userId
     * @param {Number} options.productId
     * @param {Function} callback
     */
    activityServiceUtil.checkUserWhetherLikeProduct = function(options, callback){
        const entity = new YjxUserLikeModel({
            type: 10,
            obj_type: 10,
            obj_id: options.productId,
            user_id: options.userId,
            del_flg:0
        });
        entity.findFromDB(function (error, results) {
            if(error) return callback(error, 0);
            return callback(error, results ? results.length : 0);
        });
    };


    /**
     * 刷新活动状态
     *
     * @author 王俊
     * @date 2018-08-02
     *
     * @param {Object} options
     * @param {Number} options.type 活动类型
     * @param {Function} callback
     *                      error
     */
    activityServiceUtil.refreshActivityState = function (options, callback) {
        if(options.type !== 20) {
            return callback('暂不支持的活动类型');
        }

        const totalTasks = [];

        // 1. 获取需要确认的活动列表
        totalTasks.push(function (callback) {
            const entity = new YjxActivityModel();
            const opt = {};
            entity.selectNeedAutoCheckActivityList(opt, function (error, list) {
                const data = {};
                data.actList = list || [];
                return callback(null, data);
            });
        });
        // 2. 根据时间判断是否需要更新状态
        totalTasks.push(function (data, callback) {

            data.needReCheckActs = [];
            data.updateActs = [];
             data.actList.forEach(function (actInfo) {
                 const current = moment();
                 let  state = 20;
                 if(current.isBefore(actInfo.start_time)) {
                     state = 10;
                 }
                 if(current.isAfter(actInfo.end_time)) {
                     state = 30
                 }
                 if(current.isAfter(actInfo.start_time) && current.isBefore(actInfo.end_time)) {
                     state = 20
                 }
                 // 需要更新状态
                 if(actInfo.state !== state) {
                    actInfo.needUpadte = true;
                    actInfo.newState = state;
                    data.updateActs.push(actInfo);
                 }
                 // 需要进一步确认余额的活动
                 if(actInfo.state === 20 || actInfo.newState === 20) {
                     actInfo.needCheckRemaining = true;
                     data.needReCheckActs.push(actInfo);
                 }
             });
             return callback(null, data);
        });
        // 3. 仍待确认的活动, 向 redis 查询活动余额
        totalTasks.push(function (data, callback) {
            if(!data.needReCheckActs || data.needReCheckActs.length <=0) {
                return callback(null, data);
            }
            const tasks = [];
            data.needReCheckActs.forEach(function (actInfo) {
                tasks.push(function (callback) {
                     luaUtil.getActAllRemaining([actInfo.act_id], function (error, remaining) {
                         if(error || !remaining || remaining.length !== 3) {
                             console.log(error || '获取剩余奖励出错');
                             return callback(null, null); // 单个查询出错不影响其他操作
                         }
                         actInfo.remaining = {};
                         actInfo.remaining.randomRemaining = remaining[0];
                         actInfo.remaining.likeRemaining = remaining[1];
                         actInfo.remaining.praisedRemaining = remaining[2];

                         // 奖金发放完毕关闭活动
                         if(actInfo.remaining.likeRemaining <=0 && actInfo.remaining.praisedRemaining <=0) {
                             actInfo.needUpadte = true;
                             actInfo.newState = 40; // 活动关闭
                             // 数组内不存在, 则处理
                             if(data.updateActs.indexOf(actInfo) === -1) {
                                 data.updateActs.push(actInfo);
                             }

                         }
                         return callback(null, actInfo);
                     });
                });
            });
            async.parallelLimit(tasks, 5, function (error, results) {
                return callback(error, data);
            });
        });
        // 4. 更新活动
        totalTasks.push(function (data, callback) {
            if(!data.updateActs || data.updateActs.length <=0) {
                return callback(null, null);
            }
            const tasks =[];
            data.updateActs.forEach(function (actInfo) {
                tasks.push(function (callback) {
                    const entity = new YjxActivityModel({
                        act_id: actInfo.act_id,
                        state: actInfo.newState,
                        update_by: '自动确认活动状态'
                    });
                    entity.updateToDB(function (error) {
                        // 单个更新失败,不影响其他活动
                        return callback(null, null);
                    });
                });
            });
            async.parallelLimit(tasks, 5, function (error, results) {
                 return callback(error, data);
            });
        });
        async.waterfall(totalTasks, function (error, data) {
            return callback(error, {});
        });




    };

    return activityServiceUtil;
})();

module.exports = activityServiceUtil;